package com.launch.wlfw.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.launch.wlfw.dao.AdminMapper;
import com.launch.wlfw.pojo.Admin;
import com.launch.wlfw.service.AdminService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 管理服务impl
 *
 * @author liuwei
 * @date 2023/06/30
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    /**
     * 管理映射器
     */
    @Resource
    private AdminMapper adminMapper;

    /**
     * 查询用户名和密码
     *
     * @param username 用户名
     * @param password 密码
     * @return {@link Admin}
     */
    @Override
    public Admin queryUserByNameAndPassword(String username, String password) {
        return adminMapper.queryUserByNameAndPassword(username,password);
    }


    /**
     * 找到名字
     *
     * @param admin    管理
     * @param pageNum  页面num
     * @param pageSize 页面大小
     * @return {@link PageInfo}<{@link Admin}>
     */
    @Override
    public PageInfo<Admin> findByName(Admin admin, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list = adminMapper.findByName(admin);
        return PageInfo.of(list);
    }

    /**
     * 添加管理员列表
     *
     * @param admin 管理
     * @return {@link Integer}
     */
    @Override
    public Integer addAdminList(Admin admin) {
        admin.setPassword(SecureUtil.md5(admin.getPassword()));
        admin.setRoleId(1);
        return  adminMapper.insertAdminList(admin);
    }

    /**
     * 删除管理员列表
     *
     * @param ids id
     * @return {@link Integer}
     */
    @Override
    public Integer deleteAdminList(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        for (String s: list) {
            adminMapper.deleteAdminList(Integer.valueOf(s));
        }
        return null;
    }

    @Override
    public Integer updateAdminPassword(Integer id,String oldPwd,String newPwd) {
        Admin admin =adminMapper.findAdminById(id);
        if (admin.getPassword().equals(SecureUtil.md5(oldPwd))){
            admin.setPassword(SecureUtil.md5(newPwd));
            return adminMapper.updateAdminPassword(admin);
        }else{
            return -1;
        }
    }

    @Override
    public Admin findAdminById(Integer id) {
        return adminMapper.findAdminById(id);
    }
}
